package com.unittec.zk.provider.exam.service;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.ServiceException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.unittec.zk.provider.exam.enums.JoinType;
import com.unittec.zk.provider.exam.enums.OpenType;
import com.unittec.zk.provider.exam.utils.BeanMapper;
import com.unittec.zk.provider.scope.ThreadLocalScope;
import com.unittec.zk.provider.scope.ThreadLocalScopeCache;
import com.unittec.zk.provider.utils.UUIDUtils;
import com.unittec.zk.sdk.exam.domain.ExamRepoDTO;
import com.unittec.zk.sdk.exam.request.*;
import com.unittec.zk.sdk.root.internal.exception.BusinessException;
import org.springframework.cloud.context.scope.thread.ThreadScope;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.awt.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.unittec.zk.provider.exam.mapper.ElExamMapper;
import com.unittec.zk.provider.exam.entity.ElExam;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class ElExamService extends ServiceImpl<ElExamMapper, ElExam> {

    @Resource
    private ElExamRepoService elExamRepoService;

    @Resource
    private ElExamDepartService elExamDepartService;

    /**
     * 考试-分页
     *
     * @param req201012
     * @return
     */
    public Object getExamPage(Req201012 req201012) {
        //构造条件
        LambdaQueryWrapper<ElExam> qw = new LambdaQueryWrapper<>();
        if (StrUtil.isNotBlank(req201012.getTitle())) {
            qw.like(ElExam::getTitle, req201012.getTitle());
        }
        if (null != req201012.getStartTime()) {
            qw.ge(ElExam::getStartTime, req201012.getStartTime());
        }
        if (null != req201012.getEndTime()) {
            qw.le(ElExam::getEndTime, req201012.getEndTime());
        }
        if (req201012.getOpenType() != null ) {
            qw.eq(ElExam::getOpenType, req201012.getOpenType());
        }
        //排序
        qw.orderByDesc(ElExam::getCreateTime);
        //分页查询
        IPage<Map<String, Object>> page = this.baseMapper.selectMapsPage(new Page<>(req201012.getCurrent(), req201012.getSize()), qw);
        //返回结果
        return page;
    }

    /**
     * 考试-增/改
     *
     * @param req201013
     * @return
     */
    public Object saveOrUpdateExam(Req201013 req201013) {
        // ID
        String id = req201013.getId();
        if (StrUtil.isBlank(id)) {
            id = UUIDUtils.getId();
        }

        //复制参数
        ElExam entity = new ElExam();

        // 计算分值
        this.calcScore(req201013);

        // 复制基本数据
        BeanMapper.copy(req201013, entity);
        entity.setId(id);

        // 修复状态
        if (req201013.getTimeLimit() != null
                && req201013.getTimeLimit()!=1
                && req201013.getState() != null
                && req201013.getState() == 2) {
            entity.setState(0);
        } else {
            entity.setState(req201013.getState());
        }

        // 题库组卷
        if (JoinType.REPO_JOIN.equals(req201013.getJoinType())) {
            try {
                elExamRepoService.saveAll(id, req201013.getRepoList());
            } catch (DuplicateKeyException e) {
                throw new BusinessException("不能选择重复的题库！");
            }
        }

        // 开放的部门
        if (OpenType.DEPT_OPEN.equals(req201013.getOpenType())) {
            elExamDepartService.saveAll(id, req201013.getDepartIds());
        }

        this.saveOrUpdate(entity);
        return "Success";
    }

    /**
     * 计算分值
     *
     * @param reqDTO
     */
    private void calcScore(Req201013 reqDTO) {

        // 主观题分数
        int objScore = 0;

        // 题库组卷
        if (JoinType.REPO_JOIN.equals(reqDTO.getJoinType())) {
            List<ExamRepoDTO> repoList = reqDTO.getRepoList();

            for (ExamRepoDTO item : repoList) {
                if (item.getRadioCount() != null
                        && item.getRadioCount() > 0
                        && item.getRadioScore() != null
                        && item.getRadioScore() > 0) {
                    objScore += item.getRadioCount() * item.getRadioScore();
                }
                if (item.getMultiCount() != null
                        && item.getMultiCount() > 0
                        && item.getMultiScore() != null
                        && item.getMultiScore() > 0) {
                    objScore += item.getMultiCount() * item.getMultiScore();
                }
                if (item.getJudgeCount() != null
                        && item.getJudgeCount() > 0
                        && item.getJudgeScore() != null
                        && item.getJudgeScore() > 0) {
                    objScore += item.getJudgeCount() * item.getJudgeScore();
                }
            }
        }


        reqDTO.setTotalScore(objScore);
    }

    /**
     * 考试-详情分页查
     * @param req201014
     * @return
     */
    public Object getExamDetailPage(Req201014 req201014) {
        IPage<Map<String,Object>> page = baseMapper.getExamDetailPage(new Page<>(req201014.getCurrent(),req201014.getSize()), req201014);
        return page;
    }

    /**
     * 考试-批量删
     * @param req201015
     * @return
     */
    public Object delExamByIds(Req201015 req201015) {
        this.removeByIds(req201015.getIds());
        return null;
    }

    /**
     * 考试明细
     * @param req201016
     * @return
     */
    public Object getPageDetail(Req201016 req201016) {
        List<Map<String,Object>> list = baseMapper.getPageDetail(req201016);
        return list;
    }

    /**
     * 在线考试-分页
     * @param req201017
     * @return
     */
    public Object getOnLinePage(Req201017 req201017) {
        String id = ThreadLocalScope.getAuthData().getIp();
        IPage<Map<String,Object>> page = this.baseMapper.getOnLinePage(new Page<>(req201017.getCurrent(),req201017.getSize()),req201017,id);
        return page;
    }

    /**
     * 在线考试-详情
     * @param req201018
     * @return
     */
    public Object getOnLineDetail(Req201018 req201018) {
        ElExam exam = this.getById(req201018.getId());
        Map map = exam==null?new HashMap():JSON.parseObject(JSON.toJSONStringWithDateFormat(exam,"yyyy-MM-dd HH:mm:ss"), Map.class);

        // 考试部门
        List<String> departIds = elExamDepartService.listByExam(req201018.getId());
        map.put("departIds",departIds);

        // 题库
        List<ExamRepoDTO> repos = elExamRepoService.listByExam(req201018.getId());
        map.put("repoList",repos);

        String s = JSON.toJSONString(map);
        String s1 = s.replaceAll("[A-Z]", "_$0").toLowerCase();
        return JSON.parseObject(s1,Map.class);
    }
}
